/**
 * 依据天分组
 * @param {*} data 
 * @param {*} dataKey 
 * @param {*} orderBy 
 * @returns 
 */
export function groupDataByDate(data, dataKey, orderBy = 'ASC') {
    return groupDataBy({
        data,
        dataKey
    }, {
        groupBy: 'YYYY-MM-DD',
        orderBy
    })
}

/**
 * 依据月份分组
 * @param {*} data 
 * @param {*} dataKey 
 * @param {*} orderBy 
 * @returns 
 */
export function groupDataByMonth(data, dataKey, orderBy = 'ASC') {
    return groupDataBy({
        data,
        dataKey
    }, {
        groupBy: 'YYYY-MM',
        orderBy
    })

}

/**
 * 依据年分组
 * @param {*} data 
 * @param {*} dataKey 
 * @param {*} orderBy 
 * @returns 
 */
export function groupDataByYear(data, dataKey, orderBy = 'ASC') {
    return groupDataBy({
        data,
        dataKey
    }, {
        groupBy: 'YYYY',
        orderBy
    })
}


/**
 * 数据分组工具
 * @param {*} dataInfo 
 * @param {*} config 
 * @returns 
 */
function groupDataBy(dataInfo, config) {

    let { dataKey, data } = dataInfo;
    let { groupBy = 'YYYY-MM-DD', orderBy } = config;

    // 时间排序
    data.sort((a, b) => {
        let preTime = a[dataKey];
        let afterTime = b[dataKey];
        let aTime = getThousandTimes(preTime);
        let bTime = getThousandTimes(afterTime);
        if (orderBy == 'DESC') {
            return bTime - aTime
        }
        if (orderBy == 'ASC') return aTime - bTime;
    });

    let preTag = 0;
    let result = [];
    let sonItem = [];

    data.forEach((v, index) => {
        let time = v[dataKey]
        let currentTag = timeUtil(time).formate(groupBy);
        // 新的一天
        if (currentTag != preTag) {
            preTag = currentTag;

            // 封存数据
            if (sonItem.length) {
                result.push(sonItem);
            }
            sonItem = [v];
        } else {
            sonItem.push(v);
        }

        // 最后一条
        if (index == data.length - 1) {
            result.push(sonItem)
        }
    })

    return result;
}

function timeUtil(date) {
    let dateInstance = new Date(date)

    return {
        formate: (format = 'YYYY-MM-DD') => {
            let year = dateInstance.getFullYear();
            let month = dateInstance.getMonth() + 1;
            let date = dateInstance.getDate();
            switch (format) {
                case 'YYYY-MM-DD':
                    return `${year}-${month}-${date}`
                case 'YYYY-MM':
                    return `${year}-${month}`
                case 'DD':
                    return `${date}`
                case 'MM':
                    return `${month}`
                case 'YYYY':
                    return `${year}`
            }
        }
    }
}



/**
 * 获取毫秒
 * @param {*} date 
 * @returns 
 */
function getThousandTimes(date) {
    return new Date(date).valueOf();
}


//--------------------------------------------------------
